package hu.myai.api.tick;

import hu.myai.model.TickVO;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bozbalint
 * 
 */
abstract public class AbstractTickConsumer implements TickConsumerInterface {

    /**
     * Name of the consumer
     */
    protected String name;

    /**
     * This contains the most recent tick
     * */
    protected TickVO lastTick;

    /**
     * It should be a reference and it should not be a copy of tick history
     */
    static protected List<TickVO> tickHistory = new ArrayList<TickVO>();

    /**
     * true until a new tick is not processed; false while the processing
     * */
    protected boolean isTickCompleteness = false;

    /**
     * The number of the tick data is stored in the tickHistory list I don't
     * want to let it grow till the sky
     * 
     * */
    private static final int maxHistory = 500;

    public AbstractTickConsumer() {
        tickHistory.clear();
    }

    /**
     * @return the value of name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Input of the calculation
     */
    public void addTick(TickVO tick) {

        // save the most recent tick
        lastTick = tick;

        // add the tick to the history, the first is the newest
        if (!tickHistory.contains(tick))
            tickHistory.add(0, tick);

        // new, not processed tick
        isTickCompleteness = true;

        startCalculation();

        // clean up the history time by time
        tickHistoryCleanup();
    }

    /**
     * Calculation
     * */
    protected abstract void startCalculation();

    /**
     * This check the size of tick history list. If the list size is larger then
     * the given value it truncates it. This take care of no heap memory
     * problem.
     */
    private static void tickHistoryCleanup() {
        while (tickHistory.size() > maxHistory) {
            tickHistory.remove(tickHistory.size() - 1);
        }
    }
}
